package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ReScanUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardCreateOrderByProductBean;
import com.ruike.alisurface.bean.CardCreateOrderBySlotBean;
import com.ruike.alisurface.bean.CardOrderBean;
import com.ruike.alisurface.bean.ReScanCreateOrderByProductBean;
import com.ruike.alisurface.bean.ReScanCreateOrderBySlotBean;
import com.ruike.alisurface.bean.ReScanOrderResultBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.http.MchApiHttp.reScanCreateOrderByProductUrl;
import static com.ruike.alisurface.http.MchApiHttp.reScanCreateOrderBySlotUrl;
import static com.ruike.alisurface.http.MchApiHttp.reScanPointPayUrl;

/**
 * Author: voodoo
 * CreateDate: 2023/09/26 026 上午 09:29
 * Description: 反扫支付
 */
public class PayForReverseScanningActivity extends BaseAty implements ReScanUtils.OnReScanListener {

    private List<CarGoodsBeans> shoppingCartProductList;

    @BindView(R.id.payReScan_goback_imgv)
    ImageView gobackImgv;
    @BindView(R.id.payReScan_countTime_tv)
    TextView countTimeTv;
    @BindView(R.id.payReScan_currentState_tv)
    TextView currentStateTv;
    private ShopDetailBean shopDetailBean;

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_reverse_scanning;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(120, countTimeTv, SelectPayTypeActivity.class);
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        // 计算购物车商品的总金额并展示在界面上
        shoppingCartProductList = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (shoppingCartProductList == null || shoppingCartProductList.size() <= 0) {
            showErrorTip("购物车商品为空！");
            startCountdownTimer(3, null, null);
            return;
        }
        float point = 0;
        for (CarGoodsBeans carGoodsBean : shoppingCartProductList) {
            if (carGoodsBean != null && carGoodsBean.getPrice() > 0) {
                point += carGoodsBean.getPoint();
            }
        }

        currentStateTv.setText("正在创建订单，请稍后");
        createOrder();

    }

    @OnClick({R.id.payReScan_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payReScan_goback_imgv:
                startCountdownTimer(0, null, SelectPayTypeActivity.class);
                break;
        }
    }

    /**
     * 创建订单
     */
    private void createOrder() {
        // 是否是按照货道下单
        boolean isShowSlot = ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1;
        int temp = isShowSlot ? createOrderBySlot() : createOrderByProduct();
    }

    private int createOrderBySlot() {
        L.i("按货道展示下单");

        Map<String, Integer> map = new HashMap<>();
        for (CarGoodsBeans carGoodsBean : shoppingCartProductList) {
            String slotIndex = carGoodsBean.getSlotIndexs();
            if (map.containsKey(slotIndex)) {
                map.put(slotIndex, map.get(slotIndex) + 1);
            } else {
                map.put(slotIndex, 1);
            }
        }

        List<ReScanCreateOrderBySlotBean.DetailsBean> detailsBeanList = new ArrayList<>();
        for (String key : map.keySet()) {
            ReScanCreateOrderBySlotBean.DetailsBean detailsBean = new ReScanCreateOrderBySlotBean.DetailsBean();
            detailsBean.setQuantity(map.get(key)); // 数量
            detailsBean.setSlotIndex(Integer.parseInt(key)); // 货道号
            detailsBeanList.add(detailsBean);
        }

        ReScanCreateOrderBySlotBean createBean = new ReScanCreateOrderBySlotBean();
        createBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
        createBean.setDetails(detailsBeanList);
        L.i("按货道创建的订单对象：" + createBean);

        MchApiHttp.reScanCreateOrderBySlot(createBean, this);
        return 0;
    }

    private int createOrderByProduct() {
        L.i("按商品类型展示下单");

        if (shoppingCartProductList == null || shoppingCartProductList.size() <= 0) {
            L.e("订单数据异常：" + shoppingCartProductList);
            return 0;
        }

        List<ReScanCreateOrderByProductBean.DetailsBean> detailsBeanList = new ArrayList<>();
        for (CarGoodsBeans cardGoodsBean : shoppingCartProductList) {
            ReScanCreateOrderByProductBean.DetailsBean detailsBean = new ReScanCreateOrderByProductBean.DetailsBean();
            detailsBean.setProductid(cardGoodsBean.getProductid());
            detailsBean.setQuantity(1);
            List<Integer> slotIndexList = GsonUtils.jsonArray2ModelList(cardGoodsBean.getSlotIndexs(), Integer.class);
            detailsBean.setSlotIndexs(slotIndexList);
            detailsBeanList.add(detailsBean);
        }

        ReScanCreateOrderByProductBean createBean = new ReScanCreateOrderByProductBean();
        createBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
        createBean.setDetails(detailsBeanList);
        L.i("按商品创建的订单对象：" + createBean);

        MchApiHttp.reScanCreateOrderByProduct(createBean, this);
        return 0;
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (reScanCreateOrderByProductUrl.equals(requestUrl) || reScanCreateOrderBySlotUrl.equals(requestUrl)) { // 按照货道下单返回 或者 按照商品下单返回
            // 无论按照商品下单还是按照货道下单，返回的对象都是一样的
            ReScanOrderResultBean orderBean = GsonUtils.json2Model(requestJsonStr, ReScanOrderResultBean.class);

            shopDetailBean = new ShopDetailBean(orderBean.getData().getOrder_id());
            shopDetailBean.setTotal_fee(orderBean.getData().getTotal_point());
            shopDetailBean.setPay_fee(0);
            shopDetailBean.setPromotion_fee(0);
            shopDetailBean.setDiscount_fee(0);

            List<ShopDetailBean.OrderDetailsBean> shopOrderDetailsBeanList = new ArrayList<>();
            shopOrderDetailsBeanList.clear();

            for (ReScanOrderResultBean.DataBean.DetailListBean detailsBean : orderBean.getData().getDetail_list()) {
                ShopDetailBean.OrderDetailsBean shopOrderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                shopOrderDetailsBean.setSlotTypeId(detailsBean.getSlotType()); // 货道类型
                shopOrderDetailsBean.setSlotIndex(detailsBean.getSlotIndex()); // 出货货道编号
                shopOrderDetailsBean.setQuantity(detailsBean.getQuantity()); // 出货数量
                shopOrderDetailsBeanList.add(shopOrderDetailsBean);
            }

            shopDetailBean.setDetailOrderList(shopOrderDetailsBeanList);

            currentStateTv.setText("订单创建成功，请将二维码放置于反扫器前");
            ReScanUtils.setOnReScanListener(this);
            ReScanUtils.startReadQrCode();

        }
        if (reScanPointPayUrl.equals(requestUrl)) {
            Bundle bundle = new Bundle();
            bundle.putString("pay_type", "反扫");
            bundle.putSerializable("orderBeanData", shopDetailBean);
            startActivity(PayShowShopActivity.class, bundle);
            finish();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (reScanCreateOrderByProductUrl.equals(requestUrl) || reScanCreateOrderBySlotUrl.equals(requestUrl)) {
            showErrorTip("订单创建失败");
            startCountdownTimer(3, null, SelectPayTypeActivity.class);
            return;
        }
        if (reScanPointPayUrl.equals(requestUrl)) {
            currentStateTv.setText(errorMsg);
            gobackImgv.setEnabled(true);
            ReScanUtils.startReadQrCode();
        }
    }

    @Override
    public void onReScanResultListener(boolean isSuccess, String content) {
        if (!isSuccess) {
            showErrorTip(content);
            return;
        }
        L.iTag(getClass().getSimpleName(), "获取到数据，上传通知后台扣款去");
        gobackImgv.setEnabled(false);
        currentStateTv.setText("获取到数据，正在上传订单...");
        ReScanUtils.stopReadQrCode();
//        {sessionId=651101816b6e69044d1e23a7,accountId=651101816b6e69044d1e23a6}
        String replace = content.replace("{", "").replace("}", "");
//        sessionId=651101816b6e69044d1e23a7,accountId=651101816b6e69044d1e23a6
        String[] split = replace.split(",");
//        ["sessionId=651101816b6e69044d1e23a7","accountId=651101816b6e69044d1e23a6"]

        String sessionId = "";
        String accountId = "";

        for (String tempStr : split) {
            if (tempStr.contains("sessionId")) {
                sessionId = tempStr.substring(10);
            } else if (tempStr.contains("accountId")) {
                accountId = tempStr.substring(10);
            }
        }

        L.iTag(getClass().getSimpleName(), String.format(Locale.ENGLISH, "解析到的 sessionId：%s accountId:%s", sessionId, accountId));

        MchApiHttp.reScanPointPay(shopDetailBean.getOrderId(), accountId, sessionId, this);
    }

}
